<template>
  <div>
    <el-dialog
      :visible.sync="viewDialog"
      :append-to-body="true"
      :before-close="closeViewDialog"
      class="medium-common-dialog-size">
      <div class="title-container">
        <Title title="管理视图" />
        <PlainCreateBtn @click="creatViewVisibleOpen()">新增</PlainCreateBtn>
      </div>
      <div v-loading="loading" :style="{maxHeight: maxHeight}" class="table-list">
        <el-table
          v-if="allViewData && allViewData.items.length"
          ref="orderTable"
          :data="allViewData.items"
          class="fb-table"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          fit
          hightlight-current-row>

          <el-table-column align="left" label="视图名称">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.name" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="操作" width="100">
            <template slot-scope="scope">
              <div v-if="userInfo.id === scope.row.createUserId" class="flex">
                <div class="button-text br" @click="creatViewVisibleOpen(scope.row)">编辑</div>
                <div class="button-text" @click="deleteItem(scope.row.id)">删除</div>
              </div>
              <div v-else class="flex">
                <div class="disabled button-text br">编辑</div>
                <div class="disabled button-text">删除</div>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <EmptyPlaceholder v-else />
      </div>
      <div class="flex">
        <div style="flex: 1;"/>
        <div class="pagination-area">
          <el-pagination
            v-show="allViewData.total > 0"
            :current-page="allViewData.page"
            :page-size="allViewData.perPage"
            :total="allViewData.total"
            :page-sizes="[10, 20, 50, 100, 250, 500]"
            :layout="'total, prev, pager, next, sizes'"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </div>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="creatViewVisible"
      :append-to-body="true"
      :before-close="creatViewVisibleClose"
      class="small-common-dialog-size">
      <Title title="请输入视图名称" font-size="16px" style="margin-bottom: 24px;" />
      <el-input v-model="viewName" :maxlength="50" size="small" placeholder="请输入视图名称" @keyup.enter.native="toCreateView" />
      <div class="btn-box">
        <el-button type="primary" size="small" @click="toCreateView(false)">保存</el-button>
        <el-button size="small" @click="creatViewVisibleClose">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Title from '@/components/Title';
import { createViewList, getViewList, editViewList, deleteView } from '@/api/resource';
import ElMessage from '@/utils/message';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import { showModal } from '@/utils/message';
import { mapState } from 'vuex';
export default {
  components: { Title, EmptyPlaceholder },
  props: {
    platform: {
      type: String | Number,
      default: ''
    },
    tableList: { // 当前列表展示
      type: Array,
      default: () => {
        return [];
      }
    },
    sortList: { // 当前列表展示
      type: Array,
      default: () => {
        return [];
      }
    },
    curView: {
      type: Object | String,
      default: () => ({})
    }
  },
  data() {
    return {
      viewDialog: false,
      creatViewVisible: false,
      viewName: '',
      page: 1,
      perPage: 10,
      allViewData: {
        items: [],
        total: 0
      },
      editId: null,
      editData: null,
      loading: false,
      maxHeight: ''
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    })
  },
  create() {
  },
  methods: {
    openViewDialog() {
      this.viewDialog = true;
      this.toGetViewList();
      const clientHeight = window.innerHeight;
      this.maxHeight = ((clientHeight * 4) / 5) - 142 + 'px';
    },
    closeViewDialog() {
      this.viewDialog = false;
    },
    creatViewVisibleClose() {
      this.viewName = '';
      this.creatViewVisible = false;
      this.editId = null;
    },
    creatViewVisibleOpen(item) {
      if (item && item.id) {
        this.viewName = item.name;
        this.editId = item.id;
        this.editData = item.data;
      } else {
        this.editId = null;
      }
      this.creatViewVisible = true;
    },
    toCreateView(resetList = false) {
      if (!this.viewName) {
        ElMessage.error('请输入视图名称');
        return;
      }
      const platform = this.platform || 'all';
      const tableData = {
        name: this.viewName,
        platform,
        data: JSON.stringify({ sortList: this.sortList, tableList: this.tableList })
      };
      if (this.editId) {
        tableData.id = this.editId;
        tableData.data = this.editData;
        editViewList(tableData).then(res => {
          if (res.code === 200) {
            resetList ? ElMessage.success('保存成功') : ElMessage.success('编辑成功');
            this.creatViewVisibleClose();
            this.toGetViewList();
            this.$emit('freshData');
            resetList && this.$emit('resetList');
          }
        });
      } else {
        createViewList(tableData).then(res => {
          if (res.code === 200) {
            ElMessage.success('创建成功');
            this.creatViewVisibleClose();
            this.toGetViewList(false, tableData.name);
            this.$emit('freshData');
          }
        });
      }
    },
    deleteItem(id) {
      const loclView = this.getLocalView();
      const platform = this.platform || 'all';
      showModal('是否删除当前视图配置').then(() => {
        deleteView(id).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.toGetViewList(true);
            this.$emit('freshData');
            if (loclView[platform] && loclView[platform].id === id) {
              delete loclView[platform];
              localStorage.setItem('curView', JSON.stringify(loclView));
            }
          } else {
            this.$message.error(res.message);
          }
        });
      });
    },
    getLocalView() {
      const loclView = localStorage.getItem('curView') || '{}';
      return this.jsonParse(loclView);
    },
    toGetViewList(reset = false, name) {
      if (reset) this.page = 1;
      const platform = this.platform || 'all';
      const data = {
        page: this.page,
        perPage: this.perPage,
        platform
      };
      this.loading = true;
      getViewList(data).then((res) => {
        this.loading = false;
        if (res.code === 200) {
          this.allViewData = res.data;
          if (name) {
            const item = res.data.items.find(e => e.name === name);
            this.$emit('changeView', item);
          }
        }
      }).catch(() => {
        this.loading = false;
      });
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.toGetViewList(true);
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.toGetViewList();
    },
    jsonParse(str) {
      if (typeof str !== 'string') return str;
      try {
        return JSON.parse(str);
      } catch (error) {
        console.log(error);
        return {};
      }
    },
    operateView(isEdit = false, resetList = false) {
      const item = this.curView;
      if (isEdit) {
        this.viewName = item.name;
        this.editId = item.id;
        this.editData = JSON.stringify({ sortList: this.sortList, tableList: this.tableList });
        this.toCreateView(resetList);
      } else {
        this.editId = null;
        this.creatViewVisible = true;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.table-list {
  min-height: 345px;
  @include scrollBar($width: 6px);
}
.btn-box {
  display: flex;justify-content: center;margin-top: 24px;
}
.title-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
</style>
